<template>
  <Dialog v-model="dialogVisible" title="方案模板配置" width="900px">
    <div v-loading="formLoading">
      <el-form
        ref="formRef"
        :model="formData"
        label-width="120px"
      >
        <el-form-item label="方案信息">
          <el-card class="scheme-info">
            <div class="info-row">
              <span class="label">方案名称：</span>
              <span>{{ schemeInfo.schemeName }}</span>
            </div>
            <div class="info-row">
              <span class="label">适用职业：</span>
              <span>{{ schemeInfo.professionName }}</span>
            </div>
            <div class="info-row">
              <span class="label">技能等级：</span>
              <span>{{ schemeInfo.skillLevel }}</span>
            </div>
          </el-card>
        </el-form-item>
        
        <el-form-item label="模板配置">
          <el-tabs v-model="activeTab" type="card">
            <el-tab-pane label="理论考试" name="theory">
              <template-config-panel
                v-model="formData.theoryTemplate"
                template-type="理论考试"
                :profession-code="schemeInfo.professionCode"
                :skill-level="schemeInfo.skillLevel"
              />
            </el-tab-pane>
            
            <el-tab-pane label="实操考核" name="practical">
              <template-config-panel
                v-model="formData.practicalTemplate"
                template-type="实操考核"
                :profession-code="schemeInfo.professionCode"
                :skill-level="schemeInfo.skillLevel"
              />
            </el-tab-pane>
            
            <el-tab-pane label="综合评审" name="comprehensive">
              <template-config-panel
                v-model="formData.comprehensiveTemplate"
                template-type="综合评审"
                :profession-code="schemeInfo.professionCode"
                :skill-level="schemeInfo.skillLevel"
              />
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
        
        <el-form-item label="权重配置">
          <el-table :data="weightConfig" border style="width: 100%">
            <el-table-column prop="evaluationType" label="评价类型" width="150" />
            <el-table-column label="权重比例" width="200">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.weight"
                  :min="0"
                  :max="100"
                  :precision="1"
                  controls-position="right"
                  style="width: 100%"
                />
                <span style="margin-left: 5px;">%</span>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="说明" />
          </el-table>
          
          <div class="weight-summary">
            <el-alert
              :title="`总权重：${totalWeight}%`"
              :type="totalWeight === 100 ? 'success' : 'warning'"
              :closable="false"
              show-icon
            />
          </div>
        </el-form-item>
        
        <el-form-item label="配置说明">
          <el-input
            v-model="formData.configDescription"
            type="textarea"
            :rows="3"
            placeholder="请输入配置说明"
          />
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <el-button @click="saveConfig" type="primary" :disabled="formLoading || totalWeight !== 100">
        保存配置
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import TemplateConfigPanel from './components/TemplateConfigPanel.vue'

defineOptions({ name: 'SchemeTemplateConfig' })

const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()
const activeTab = ref('theory')

const schemeInfo = reactive({
  id: undefined,
  schemeName: '',
  professionName: '',
  professionCode: '',
  skillLevel: ''
})

const formData = reactive({
  theoryTemplate: {
    templateId: undefined,
    isEnabled: false,
    timeLimit: 120,
    passScore: 60
  },
  practicalTemplate: {
    templateId: undefined,
    isEnabled: false,
    timeLimit: 180,
    passScore: 60
  },
  comprehensiveTemplate: {
    templateId: undefined,
    isEnabled: false,
    timeLimit: 60,
    passScore: 60
  },
  configDescription: ''
})

const weightConfig = ref([
  {
    evaluationType: '理论考试',
    weight: 40,
    description: '理论知识考核权重'
  },
  {
    evaluationType: '实操考核',
    weight: 50,
    description: '实际操作技能考核权重'
  },
  {
    evaluationType: '综合评审',
    weight: 10,
    description: '综合素质评审权重'
  }
])

const totalWeight = computed(() => {
  return weightConfig.value.reduce((sum, item) => sum + (item.weight || 0), 0)
})

/** 打开弹窗 */
const open = async (scheme: any) => {
  dialogVisible.value = true
  Object.assign(schemeInfo, scheme)
  await loadTemplateConfig()
  resetForm()
}

/** 加载模板配置 */
const loadTemplateConfig = async () => {
  try {
    formLoading.value = true
    
    // TODO: 调用获取方案模板配置的API
    // const config = await getSchemeTemplateConfig(schemeInfo.id)
    // if (config) {
    //   Object.assign(formData, config)
    //   weightConfig.value = config.weightConfig || weightConfig.value
    // }
  } catch (error) {
    console.error('加载模板配置失败:', error)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.theoryTemplate = {
    templateId: undefined,
    isEnabled: false,
    timeLimit: 120,
    passingScore: 60
  }
  formData.practicalTemplate = {
    templateId: undefined,
    isEnabled: false,
    timeLimit: 180,
    passingScore: 60
  }
  formData.comprehensiveTemplate = {
    templateId: undefined,
    isEnabled: false,
    timeLimit: 60,
    passingScore: 60
  }
  formData.configDescription = ''
  
  weightConfig.value = [
    { evaluationType: '理论考试', weight: 40, description: '理论知识考核权重' },
    { evaluationType: '实操考核', weight: 50, description: '实际操作技能考核权重' },
    { evaluationType: '综合评审', weight: 10, description: '综合素质评审权重' }
  ]
}

/** 保存配置 */
const saveConfig = async () => {
  if (totalWeight.value !== 100) {
    ElMessage.error('权重总和必须等于100%')
    return
  }
  
  try {
    formLoading.value = true
    
    const configData = {
      schemeId: schemeInfo.id,
      templateConfig: formData,
      weightConfig: weightConfig.value,
      configDescription: formData.configDescription
    }
    
    // TODO: 调用保存方案模板配置的API
    // await saveSchemeTemplateConfig(configData)
    
    ElMessage.success('模板配置保存成功')
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('保存模板配置失败:', error)
    ElMessage.error('保存模板配置失败')
  } finally {
    formLoading.value = false
  }
}

defineExpose({ open })
</script>

<style scoped>
.scheme-info {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.label {
  font-weight: bold;
  min-width: 80px;
  color: #606266;
}

.weight-summary {
  margin-top: 15px;
}

:deep(.el-tabs__content) {
  padding: 20px 0;
}
</style>
